package com.kmenpin.Wxmp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kmenpin.HttpClientHelper;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * refer to: https://blog.csdn.net/u013289808/article/details/82896971
 */
public class WxAuth {

    /**
     * Use the code to get WeChat user information
     * @param wxApp
     * @param code
     * @return
     * @throws Exception
     */
    public WxUser code2Wxuser (WxApp wxApp, String code) throws Exception {
        Properties settings = new Properties();

        // 读取相关配置
        InputStream inputStream = WxAuth.class.getClassLoader().getResourceAsStream("setting.properties");
        try {
            settings.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String url = new StringBuilder().append(settings.getProperty("code2sessionUrl"))
                .append("?appid=" + wxApp.getAppid())
                .append("&secret=" + wxApp.getSecret())
                .append("&js_code=" + code)
                .append("&grant_type=authorization_code")
                .toString();

        String result = HttpClientHelper.doGet(url);

        JSONObject jsonObj = JSON.parseObject(result);
        if (jsonObj.containsKey("errcode") && jsonObj.getInteger("errcode") != 0) {
            throw new Exception("Failed fetch Openid: " + result);
        }
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(jsonObj.getString("openid"));
        wxUser.setSessionKey(jsonObj.getString("session_key"));
        wxUser.setUnionid(jsonObj.getString("unionId"));

        return wxUser;
    }

    public WxUser code2WxuserB (String code) throws Exception {
        if (code.equals("mmmmCode")) {
            throw new Exception("Exception is thhhhrowing!");
        }
        WxUser wxUser = new WxUser();
        wxUser.setOpenid("Mocked ooooooopenIIIIIIIIIIId");
        return wxUser;
    }
}
